import argparse
import subprocess,os
from time import sleep
import threading
import logging as log

logfile = 'nw.log'
log.basicConfig(filename=logfile,level=log.INFO,format='%(asctime)s %(message)s',datefmt='%Y-%d-%m %I:%M:%S')

class NetSwitch:
    def __init__(self):
        self.status = 0
        self.rfile = './remote.txt'
        self.ifname = 'Ethernet0'
        self.netsub =['10.10','10.30']
        # self.deleteRfile()

    def deleteRfile(self):
        if os.path.exists(self.rfile):
            os.remove(self.rfile)
    def createRfile(self):
        f = open(self.rfile, 'w')
        f.close()
    def run_cmd(self,command):
        try:
            result = subprocess.run(command, shell=True, capture_output=True, text=True)
            if result.returncode == 0:
                output = result.stdout.strip()
            else:
                output = result.stderr.strip()
        except Exception as e:
            output = str(e)
        return output

    def get_conType(self):
        FIND3389CON = 'netstat -ano |findstr 3389|findstr ESTABLISHED'
        pro=self.run_cmd(FIND3389CON)
        re=pro.find('ESTABLISHED')
        if re > 0: #有远程用户连接
            re1 = pro.split()
            # print(re1)
            re2 = re1[2][0:5]
            if re2 in ['10.30','10.10','10.20']:  #判断是否内网
                self.status = 1   # 是内网连接
            else:
                self.status = 2   # 是外网连接
        else:
            self.status = 0


    def get_3389info(self):
        while True:
            self.get_conType()
            sleep(2)
            if not os.path.exists(self.rfile):
                self.switch_net()
                self.createRfile()


    def switch_net(self):
        if self.status == 1:
            print('当前远程网络连接类型: 内网')
            log.info('当前远程网络连接类型: 内网')
            cmd1= 'route change 0.0.0.0 mask 0.0.0.0 10.10.0.1 metric 10 if 14'
            self.run_cmd(cmd1)
            print('网络出口已经切换为家宽出口。')
            log.info('网络出口已经切换为家宽出口。')

        elif self.status == 2:
            print('当前远程网络连接类型: 外网')
            log.info('当前远程网络连接类型: 外网')
            cmd1 = 'route change 0.0.0.0 mask 0.0.0.0 10.30.0.1 metric 10 if 14'
            self.run_cmd(cmd1)
            print('网络出口已经切换为静态线路出口。')
            log.info('网络出口已经切换为静态线路出口。')
        else:
            cmd1 = 'route change 0.0.0.0 mask 0.0.0.0 10.30.0.1 metric 10 if 14'
            self.run_cmd(cmd1)
            print('当前没有远程连接到本地网络-')
            log.info('当前没有远程连接到本地网络-')
        r = self.run_cmd('curl ipinfo.io')
        log.info(r)
        print(r)


if __name__ == '__main__':
    args = argparse.ArgumentParser(description='远程线路切换脚本V2')
    args.add_argument('-i','--ifname',type=str,default='Ethernet0',help='网卡名称')
    args.add_argument('-n','--netsub',type=list,default=['10.30'],help='内外网段')
    arg = args.parse_args()


    nw = NetSwitch()

    nw.ifname = arg.ifname
    nw.netsub = arg.netsub
    log.info('检测线程启动...')
    t1 = threading.Thread(target=nw.get_3389info)
    t1.start()
    x = nw.status
    while True:
        if x != nw.status:
            x = nw.status
            log.info('网络原创连接发生变化{0} 变化后的连接类型为{1}'.format(nw.status,x))
            nw.deleteRfile()
        sleep(1)
# 增加日志
# 增加配置信息